<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type { AreaItem } from '@/apis/model/resolve'
import { Message } from '@arco-design/web-vue'
// import {
//   addApiResolveRegionApi,
//   updateApiResolveRegionApi,
// } from '@/apis/modules/resolve/area'
import { addCdnDomainApi, updateCdnDomainApi } from '@/apis/modules/cdn.ts'
import { getDnsDomainListApi } from '@/apis/modules/dns'
// import { getApiResolveDomainsApi } from '@/apis/modules/resolve/domain'

interface IProp {
  record?: AreaItem
  appTypeList?: OptionItem[]
}
const props = withDefaults(defineProps<IProp>(), {})
const emit = defineEmits(['reload'])
const visible = defineModel<boolean>('visible', { required: true })
const title = computed(() => (props.record?.id ? '编辑域名' : '新建域名'))
const formRef = ref<FormInstance>()
const dnsNameOptions = ref<LabelValue[]>([])
const formState = ref({
  name: '',
  app_id: '',
  type: undefined,
  remark: '',
  cname: '',
})
const appStore = useAppStore()
const appList = computed<OptionItem[]>(() => {
  return appStore.appList || []
})

const disabledType1 = ref(true)
const disabledType2 = ref(true)
const disabledDomain = ref(true)

const app_id_options = ref([])

const rules: Record<string, FieldRule> = {
  app_id: { required: true, message: '请选择所属应用' },

  type: { required: true, message: '请选择域名类型' },
  name: {
    required: true,
    validator(value, callback) {
      // const reg = /(?=^.{3,253}$)(?!((?:.*(?:(?:--)|(?:\.-)|(?:-\.))[^.])|(?:^-.*)))(?:[\w\-]{1,63}\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
      const reg
        = /(?=^.{3,253}$)(?!.*(?:--|\.-|-\.)[^.]|^-.*)(?:[\w-]{1,63}\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i
      // const reg = /^$/
      if (!value) {
        callback('请选择域名')
        return
      }
      if (!reg.test(value)) {
        callback('域名格式不正确')
        return
      }
      callback()
    },
  },
  cname: cnameRules,
}

function handleOpen() {
  // try {
  //   getDnsDomainList()
  // } catch (error) {
  //   console.error(error)
  // }
  app_id_options.value = props.appTypeList || []
  if (props.record) {
    formState.value.app_id = props.record.app_id!
    formState.value.name = props.record.name!
    formState.value.type = props.record.type!
    formState.value.remark = props.record.remark!
    formState.value.cname = props.record?.cname?.replace('hop-', '') ?? ''
    getDnsDomainList()
  }
}

async function getDnsDomainList() {
  const res = await getDnsDomainListApi({
    limit: 0,
    app_id: formState.value.app_id,
  })
  const list = res.list ?? []
  disabledDomain.value = false
  dnsNameOptions.value = list
    .map(item => ({ label: item.name!, value: item.name! }))
    .filter(Boolean)
}

async function refreshDnsDomainList() {
  await getDnsDomainList()

  const groupExists = dnsNameOptions.value.some(
    item => item.value === formState.value.name,
  )
  if (!groupExists) {
    formState.value.name = ''
  }

  Message.success('更新成功')
}

async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error)
    return false

  const fn = props.record ? updateCdnDomainApi : addCdnDomainApi
  const data = props.record
    ? {
        id: props.record.id!,
        ...formState.value,
        cname: `hop-${formState.value.cname}`.toLocaleLowerCase(),
      }
    : formState.value
  await fn(data).then(() => {
    Message.success('操作成功')
    visible.value = false
    emit('reload')
  })
}

function handleClose() {
  formRef.value?.resetFields()
  formState.value.app_id = ''
  formState.value.name = ''
  formState.value.type = undefined
  formState.value.remark = ''
  formState.value.cname = ''
  disabledType1.value = true
  disabledType2.value = true
}

function handleJump() {
  window.open('/sys/system-domains/domain-list?type=open', '_target')
}

function changeAppID(value: string) {
  const apps = app_id_options.value.filter(item => item.value === value)
  disabledType1.value = false
  disabledType2.value = false

  if (apps.length > 0) {
    apps.forEach((app) => {
      if (app.type === 1) {
        disabledType1.value = true
      }
      if (app.type === 2) {
        disabledType2.value = true
      }
    })
  }
  getDnsDomainList()
  formState.value.name = ''
}

function handleName() {
  formState.value.cname = randomCname()
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    :title="title"
    :width="480"
    ok-text="保存"
    :mask-closable="false"
    :before-open="handleOpen"
    :before-ok="handleSubmit"
    :before-close="handleClose"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :rules="rules"
      :model="formState"
    >
      <a-form-item
        label="所属应用"
        field="app_id"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.app_id"
          placeholder="请选择所属应用"
          :options="appList"
          :disabled="!!props.record?.id"
          @change="changeAppID"
        />
      </a-form-item>

      <a-form-item
        label="域名类型"
        field="type"
        asterisk-position="end"
      >
        <a-radio-group v-model="formState.type">
          <a-radio
            :value="1"
            :disabled="disabledType1"
          >
            接入域名
          </a-radio>
          <a-radio
            :value="2"
            :disabled="disabledType2"
          >
            转换域名
          </a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item
        v-if="!(props.record?.id && formState.type === 2)"
        label="域名"
        field="name"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.name"
          placeholder="请选择域名"
          :options="dnsNameOptions"
          show-footer-on-empty
          not-found-content="请前往DNS 账户新建数据"
          :disabled="disabledDomain"
        >
          <template #footer>
            <div
              class="h-8 flex cursor-pointer items-center gap-x-1 px-3 text-[#00A65B] leading-8"
              @click="handleJump"
            >
              <span class="text-xs leading-[19px]">新建域名</span>
              <i-icons-jump size="14px" />
            </div>
          </template>
        </a-select>
        <a-button
          class="ml-2 w-8"
          type="outline"
          :disabled="disabledDomain"
          @click="refreshDnsDomainList"
        >
          <div class="w-8 flex items-center justify-center">
            <i-icons-refresh
              size="14px"
              class="h-14px! w-14px!"
            />
          </div>
        </a-button>
      </a-form-item>

      <a-form-item
        v-if="!!(props.record?.id && formState.type === 2)"
        label="CNAME"
        field="cname"
        hide-asterisk
      >
        <section class="cloud-diverse-select w-full flex items-center">
          <a-input
            v-model="formState.cname"
            placeholder="请输入"
            class="h-32px"
            :max-length="20"
          >
            <template #prepend>
              hop -
            </template>
            <template #suffix>
              <i-icons-refresh
                class="cursor-pointer !h-14px !w-14px hover:text-1"
                @click="handleName"
              />
            </template>
          </a-input>
          <!-- <span class="cname_dot">.</span> -->
          <a-select
            v-model="formState.name"
            :options="dnsNameOptions"
            placeholder="请选择域名"
            style="
              border-top: 1px solid #dfe2e5;
              border-right: 1px solid #dfe2e5;
              border-bottom: 1px solid #dfe2e5;
              background: #f7f8fa;
              border-radius: 0px 8px 8px 0px !important;
            "
          >
            <template #footer>
              <div style="padding: 6px 0 6px 8px">
                <a-link
                  :hoverable="false"
                  @click="handleJump"
                >
                  新建域名
                  <i-icons-edit
                    size="14px"
                    class="ml-1 h-14px! w-14px!"
                  />
                </a-link>
              </div>
            </template>
          </a-select>
          <a-button
            class="ml-2 w-8"
            type="outline"
            :disabled="disabledDomain"
            @click="refreshDnsDomainList"
          >
            <div class="w-8 flex items-center justify-center">
              <i-icons-refresh
                size="14px"
                class="h-14px! w-14px!"
              />
            </div>
          </a-button>
        </section>
      </a-form-item>

      <a-form-item
        label="备注"
        field="remark"
        asterisk-position="end"
      >
        <a-textarea
          v-model="formState.remark"
          :max-length="200"
          show-word-limit
          :auto-size="{ maxRows: 5, minRows: 5 }"
          placeholder="请输入备注"
        />
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>

<style lang="less" scoped>
.cloud-diverse-select {
  :deep(.arco-input-prepend) {
    border-radius: 8px 0px 0px 8px;
    border-top: 1px solid var(--border-2, #e5e6eb);
    border-left: 1px solid var(--border-2, #e5e6eb);
    border-bottom: 1px solid var(--border-2, #e5e6eb);
    border-right: none;
  }

  :deep(.arco-input-wrapper) {
    width: 200px;
    //border-left: none !important;
    border-radius: 0 !important;
  }

  :deep(.arco-select-view) {
    padding-left: 4px;
    border-left: none;
    border-radius: 0px 8px 8px 0px;
  }
}

:deep(.arco-btn-disabled) {
  background-color: rgb(247, 248, 250) !important;
}
</style>
